<?php

namespace app\admin\library\traits;

use Exception;
use think\facade\Request;
use think\facade\Lang;

/**
 * 多语言trait类
 * 若需修改此类方法：请复制方法至对应控制器后进行重写
 */
trait Translateable
{
    public function getAttr($name)
    {
        if (isset($this->translatable) && in_array($name, $this->translatable)) {
            $lang = Lang::getLangSet();
            $translations = $this->translations()->where('lang',$lang)->find();

            if($translations){
                return $translations[$name];
            }
        }

        return parent::getAttr($name);
    }
    
    public static function onAfterWrite($model)
    {
        $transfields = Request::post('translations/a');
        if($transfields){
            $model->translations()->saveAll($transfields);
        }
    }
}